package other.edan.system.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.http.RkhdHttpClient;
import com.rkhd.platform.sdk.http.RkhdHttpData;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: OpenApiUtils
 * Description: TODO
 * date: 2023/8/29
 *
 * @author Arende
 */
public class OpenApiUtils {

//    public static void main(String[] args) {
//        RkhdHttpData data = new RkhdHttpData();
//        data.setCall_type("GET");
//        data.setCallString("/rest/data/v2.0/xobjects/contact/description");
//
//        try {
//            String response = RkhdHttpClient.instance().performRequest(data);
//            LoggerUtils.debug("获取指定通用选项集的信息：" + response);
//            JSONObject json = JSONObject.parseObject(response);
//            if (json.getString("code").equals("200")) {
//                List<String> apiKeyList = JSONObject.parseArray(JSONArray.toJSONString(json.getJSONObject("data").getJSONArray("fields")), Map.class).stream().map(x -> x.get("apiKey").toString()).collect(Collectors.toList());
//                System.out.println(apiKeyList);
//            }
//        } catch (Exception e) {
//            LoggerUtils.error("获发生异常。");
//        }
//    }

    public static void main(String[] args) {
        OpenApiUtils openApiUtils = new OpenApiUtils();
        JSONArray globalPicks = openApiUtils.getGlobalPicks("currencyUnit");
        System.out.println(globalPicks);
    }

    /**
     * 获取指定通用选项集
     *
     * @param globalPickApiKey
     * @return
     */
    public static JSONArray getGlobalPicks(String globalPickApiKey) {
        RkhdHttpData data = new RkhdHttpData();
        data.setCall_type("GET");
        data.setCallString("/rest/metadata/v2.0/settings/globalPicks/" + globalPickApiKey);

        JSONArray resultArray = new JSONArray();

        try {
            String response = RkhdHttpClient.instance().performRequest(data);
            LoggerUtils.debug("获取指定通用选项集的信息：" + response);
            JSONObject json = JSONObject.parseObject(response);
            if (json.getString("code").equals("0")) {
                resultArray = json.getJSONObject("data").getJSONObject("records").getJSONArray("pickOption");
            }
        } catch (Exception e) {
            LoggerUtils.error("获取通用选项集【" + globalPickApiKey + "】发生异常。");
        }
        return resultArray;
    }

    /**
     * 通用选项集根据apiKey获取code
     *
     * @param globalPicks
     * @param apiKey
     * @return
     */
    public static Integer getGlobalPicksApiKey(JSONArray globalPicks, String apiKey) {
        for (Object object : globalPicks) {
            JSONObject globalPick = JSONObject.parseObject(JSONObject.toJSONString(object), JSONObject.class);
            if (null != globalPick && null != apiKey && apiKey.equals(globalPick.getString("optionApiKey"))) {
                return globalPick.getInteger("optionCode");
            }
        }
        return 0;
    }

    /**
     * 通用选项集根据apiKey获取code
     *
     * @param globalPicks
     * @param apiKey
     * @return
     */
    public static Integer getCurrencyUnitGlobalPicksApiKey(JSONArray globalPicks, String apiKey) {
        for (Object object : globalPicks) {
            JSONObject globalPick = JSONObject.parseObject(JSONObject.toJSONString(object), JSONObject.class);
            String[] split = globalPick.getString("optionLabelKey").split("\\.");
            if (split[3].equals(apiKey)) {
                return globalPick.getInteger("optionCode");
            }
        }
        return 0;
    }

    /**
     * 通用选项集根据optionLabel获取code
     *
     * @param globalPicks
     * @param optionLabel
     * @return
     */
    public static Integer getGlobalPicksOptionCode(JSONArray globalPicks, String optionLabel) {
        for (Object object : globalPicks) {
            JSONObject globalPick = JSONObject.parseObject(JSONObject.toJSONString(object), JSONObject.class);
            if (null != globalPick && null != optionLabel && optionLabel.equals(globalPick.getString("optionLabel"))) {
                return globalPick.getInteger("optionCode");
            }
        }
        return 0;
    }

    /**
     * 通用选项集根据code获取optionLabel
     *
     * @param globalPicks
     * @param code
     * @return
     */
    public static String getGlobalPicksLabelByCode(JSONArray globalPicks, Integer code) {
        for (Object object : globalPicks) {
            JSONObject globalPick = JSONObject.parseObject(JSONObject.toJSONString(object), JSONObject.class);
            if (null != globalPick && null != code && code.equals(globalPick.getInteger("optionCode"))) {
                return globalPick.getString("optionLabel");
            }
        }
        return "";
    }

    /**
     * 通用选项集根据code获取optionLabel
     *
     * @param globalPicks
     * @param code
     * @return
     */
    public static String getGlobalPicksApiKeyByCode(JSONArray globalPicks, Integer code) {
        for (Object object : globalPicks) {
            JSONObject globalPick = JSONObject.parseObject(JSONObject.toJSONString(object), JSONObject.class);
            if (null != globalPick && null != code && code.equals(globalPick.getInteger("optionCode"))) {
                return globalPick.getString("optionApiKey");
            }
        }
        return "";
    }

    /**
     * 获取客户信息
     *
     * @param accountFNumberList
     * @return
     */
    public static List<Account> getAccountList(List<String> accountFNumberList) {
        List<Account> accountList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(accountFNumberList, 40);
        for (List<String> accountIds : lists) {
            String sql = "select id,automaticCode__c,erpCode__c,accountName from account where automaticCode__c in (" + listToString(accountIds) + ") or erpCode__c in (" + listToString(accountIds) + ")";
            List<Account> accounts = HCXObjectService.queryAll(sql);
            if (accounts.size() > 0) {
                accountList.addAll(accounts);
            }
        }
        return accountList;
    }

    /**
     * 获取客户信息（根据客户ids）
     *
     * @param accountIdList
     * @return
     */
    public static List<Account> getAccountListById(List<Long> accountIdList) {
        List<Account> accountList = new ArrayList<>();
        List<List<Long>> lists = HCXObjectService.splitList(accountIdList, 40);
        for (List<Long> accountIds : lists) {
            String sql = "select id,sales__c,cooperativeSalesOne__c,cooperativeSalesTwo__c,cooperativeRate3__c,cooperativeRate1__c,cooperativeRate2__c from account where id in (" + StringUtils.join(accountIds, ",") + ")";
            List<Account> accounts = HCXObjectService.queryAll(sql);
            if (accounts.size() > 0) {
                accountList.addAll(accounts);
            }
        }
        return accountList;
    }


    /**
     * 获取用户信息
     *
     * @param FSalerIdList
     * @return
     */
    public static List<User> getUserInfoList(List<String> FSalerIdList) {
        List<User> userList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(FSalerIdList, 60);
        for (List<String> userNos : lists) {
            String sql = "select id,name,employeeCode from user where employeeCode in (" + String.join(",", userNos) + ")";
            List<User> users = HCXObjectService.queryAll(sql);
            if (users.size() > 0) {
                userList.addAll(users);
            }
        }
        return userList;
    }

    /**
     * 获取部门信息
     *
     * @param FSaleDeptIdList
     * @return
     */
    public static List<Department> getDepartmentList(List<String> FSaleDeptIdList) {
        List<Department> departmentList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(FSaleDeptIdList, 60);
        for (List<String> departNos : lists) {
            String sql = "select id,departCode from department where departCode in (" + String.join(",", departNos) + ")";
            List<Department> departments = HCXObjectService.queryAll(sql);
            if (departments.size() > 0) {
                departmentList.addAll(departments);
            }
        }
        return departmentList;
    }

    /**
     * 获取产品信息
     *
     * @param FMaterialIdFNumberList
     * @return
     */
    public static List<Product> getProductList(List<String> FMaterialIdFNumberList) {
        List<Product> productList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(FMaterialIdFNumberList, 60);
        for (List<String> productNos : lists) {
            String sql = "select id,fNumber__c from product where fNumber__c in (" + listToString(productNos) + ")";
            List<Product> products = HCXObjectService.queryAll(sql);
            if (products.size() > 0) {
                productList.addAll(products);
            }
        }
        return productList;
    }

    /**
     * 获取产品目录信息
     *
     * @param codeNumberList
     * @return
     */
    public static List<ProductCategory> getProductCategoryList(List<String> codeNumberList) {
        List<ProductCategory> productCategoryList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(codeNumberList, 60);
        for (List<String> productNos : lists) {
            String sql = "select id,code__c from productCategory where code__c in (" + listToString(productNos) + ")";
            List<ProductCategory> productCategories = HCXObjectService.queryAll(sql);
            if (productCategories.size() > 0) {
                productCategoryList.addAll(productCategories);
            }
        }
        return productCategoryList;
    }

    /**
     * 获取订单信息
     *
     * @param fIdList
     * @return
     */
    public static List<Order> getOrderList(List<String> fIdList) {
        List<Order> orderList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(fIdList, 60);
        for (List<String> orderFIdS : lists) {
            String sql = "select id,fId__c from _order where fId__c in (" + String.join(",", orderFIdS) + ")";
            List<Order> orders = HCXObjectService.queryAll(sql);
            if (orders.size() > 0) {
                orderList.addAll(orders);
            }
        }
        return orderList;
    }

    /**
     * 获取订单信息
     *
     * @param idList
     * @return
     */
    public static List<Order> getOrderListById(List<Long> idList) {
        List<Order> orderList = new ArrayList<>();
        List<List<Long>> lists = HCXObjectService.splitList(idList, 50);
        for (List<Long> list : lists) {
            String sql = "select id,fId__c,fMargin__c,fRemainOutQty__c,fBillAllAmount__c from _order where id in (" + StringUtils.join(list, ",") + ")";
            List<Order> orders = HCXObjectService.queryAll(sql);
            if (orders.size() > 0) {
                orderList.addAll(orders);
            }
        }
        return orderList;
    }

    /**
     * 获取订单信息
     *
     * @param fIdList
     * @return
     */
    public static List<Order> getOrderListByBillNo(List<String> fIdList) {
        List<Order> orderList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(fIdList, 40);
        for (List<String> orderFIdS : lists) {
            String sql = "select id,fBillNo__c,currencyRate from _order where fBillNo__c in (" + listToString(orderFIdS) + ")";
            List<Order> orders = HCXObjectService.queryAll(sql);
            if (orders.size() > 0) {
                orderList.addAll(orders);
            }
        }
        return orderList;
    }

    /**
     * 根据订单fId获取订单明细信息
     *
     * @param fIdList
     * @return
     */
    public static List<OrderProduct> getOrderDetailListByFid(List<String> fIdList) {
        List<OrderProduct> orderProductList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(fIdList, 60);
        for (List<String> list : lists) {
            String sql = "select id,name,fId__c from orderProduct where fId__c in (" + String.join(",", list) + ")";
            List<OrderProduct> orders = HCXObjectService.queryAll(sql);
            if (orders.size() > 0) {
                orderProductList.addAll(orders);
            }
        }
        return orderProductList;
    }

    /**
     * 根据订单fId获取订单明细信息
     *
     * @param fIdList
     * @return
     */
    public static List<OrderProduct> getOrderDetailListByName(List<String> fIdList) {
        List<OrderProduct> orderProductList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(fIdList, 60);
        for (List<String> list : lists) {
            String sql = "select id,name,orderId,fId__c from orderProduct where name in (" + String.join(",", list) + ")";
            List<OrderProduct> orders = HCXObjectService.queryAll(sql);
            if (orders.size() > 0) {
                orderProductList.addAll(orders);
            }
        }
        return orderProductList;
    }

    /**
     * 获取订单信息
     *
     * @param fEntryIdList
     * @return
     */
    public static List<OrderProduct> getOrderDetailList(List<String> fEntryIdList) {
        List<OrderProduct> orderProductList = new ArrayList<>();
        List<List<String>> lists = HCXObjectService.splitList(fEntryIdList, 60);
        for (List<String> orderFIdS : lists) {
            String sql = "select id,orderId,fEntryID__c from orderProduct where fEntryID__c in (" + String.join(",", orderFIdS) + ")";
            List<OrderProduct> orderProducts = HCXObjectService.queryAll(sql);
            if (orderProducts.size() > 0) {
                orderProductList.addAll(orderProducts);
            }
        }
        return orderProductList;
    }

    public static String listToString(List<String> ids){
        return JSONObject.toJSON(ids).toString().replace("[", "").replace("]", "").replaceAll("\"", "'");
    }
}
